package freespiritsocial.io.user.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import androidx.navigation.fragment.findNavController
import androidx.navigation.navOptions
import com.facebook.CallbackManager
import com.lishuaihua.toast.ToastUtils
import com.sendbird.android.SendBirdException
import com.sendbird.android.SendBirdPushHelper
import freespiritsocial.io.user.BuildConfig
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseNoBindActivity
import freespiritsocial.io.user.chat.ConnectionManager
import freespiritsocial.io.user.data.model.UploadPostEvent
import freespiritsocial.io.user.data.model.bean.UpdateBean
import freespiritsocial.io.user.ext.goLogin
import freespiritsocial.io.user.ext.goMain
import freespiritsocial.io.user.ext.showDialogExt
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.util.PushUtils
import freespiritsocial.io.user.viewmodel.MainViewModel
import freespiritsocial.io.user.viewmodel.viewmodelStore.AccountViewModelOwner
import freespiritsocial.io.user.viewmodel.viewmodelStore.PostListViewModelOwner
import me.hgj.jetpackmvvm.base.BaseApp
import me.hgj.jetpackmvvm.callback.livedata.UnPeekLiveData
import me.hgj.jetpackmvvm.ext.*
import me.hgj.jetpackmvvm.util.StatusBarUtil


class MainAct: BaseNoBindActivity<MainViewModel>() {
    //注意注册完成销毁viewModel
    val accountViewModelOwner by lazy(LazyThreadSafetyMode.NONE) {
        AccountViewModelOwner()
    }
    val exploreViewModelOwner by lazy(LazyThreadSafetyMode.NONE) {
        PostListViewModelOwner()
    }
    private var rootViewVisibleHeight //纪录根视图的显示高度
            = 0


    val callbackManager: CallbackManager by lazy {
        CallbackManager.Factory.create()
    }

    val curPostId: UnPeekLiveData<Long?> = UnPeekLiveData()

    val nav get() = supportFragmentManager.findFragmentById(R.id.host_fragment)?.findNavController()

    override fun layoutId(): Int = R.layout.activity_main

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.data?.getQueryParameter("id")?.let {
            curPostId.postValue(it.toLongOrNull())
        }
        val nav1 = nav ?: return
        val type = intent?.extras?.getString("type")?.toInt() ?: return
        if (type != 3 && nav1.currentDestination?.label?.contains("NotificationsFrg",true) == false) {
            nav1.navigateAction(R.id.notificationsFrg)
            appViewModel.userinfo.value?.let {
                it.isRead = true
                appViewModel.userinfo.value = it
            }
        } else if (type == 3) {
            if (nav1.currentDestination?.label?.contains("MainFrg",true) == false)
                nav1.navigateAction(R.id.mainFrg,navOptions = navOptions {
                    popUpTo(R.id.mainFrg) { inclusive = false }
                })
            eventViewModel.changeMainTag.postValue(0)

        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.darkMode(this)

        window.decorView.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            window.decorView.getWindowVisibleDisplayFrame(r)
            val visibleHeight = r.height()
            if (rootViewVisibleHeight == 0) {
                rootViewVisibleHeight = visibleHeight;
                return@addOnGlobalLayoutListener
            }

            //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
            if (rootViewVisibleHeight == visibleHeight) {
                return@addOnGlobalLayoutListener
            }

            //根视图显示高度变小超过200，可以看作软键盘显示了
            eventViewModel.keyBoardShowEvent.postValue(rootViewVisibleHeight - visibleHeight > 200)
            rootViewVisibleHeight = visibleHeight
        }
        mViewModel.checkUpdate {
            showUpdateDialog(it)
        }
        nav?.apply {
            setGraph(
                when {
                    CacheUtil.isLogin() -> (R.navigation.main_navation)
//                    else -> (R.navigation.main_navation)
                    else -> (R.navigation.login_navation)
                }
            )
        }
    }

    override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
        callbackManager.onActivityResult(requestCode,resultCode,data)
        super.onActivityResult(requestCode,resultCode,data)
    }

    override fun createObserver() {
        super.createObserver()
        appViewModel.chatConnectStatus.observe(this) { success ->
            if (success) return@observe

            PushUtils.unregisterPushHandler(object: SendBirdPushHelper.OnPushRequestCompleteListener {
                override fun onComplete(p0: Boolean,p1: String?) {
                    ConnectionManager.logout {}
                }

                override fun onError(p0: SendBirdException?) {
                }
            })
        }

        eventViewModel.toast.observe(this) {
            it?.let {
                ToastUtils.show(it)
            }
        }
        appViewModel.toast.observe(this) {
            it?.let {
                ToastUtils.show(it)
            }
        }
        appViewModel.userinfo.observe(this) {
            if (it == null)
                exploreViewModelOwner.viewModelStore.clear()
        }
        (application as BaseApp).errorViewModel.errorEvent.observe(this) {
            if (CacheUtil.isLogin().not()) return@observe
            when (it) {
                SINGLE_LOGGED -> {
                    nav?.goLogin()
                    showDialogExt(
                        "Duplicate login detected, Please try again.",""
                    )
                }
                ACCOUNT_DELETE -> {
                    nav?.goLogin()
                }
                ACCOUNT_DISABLE -> {
                    showDialogExt(
                        "Your account has been suspended. Please contact<br> <font color =${"#3063F0"}><u>info@freespiritsocial.io</u></font>",
                        ""
                    ) {
                        nav?.goLogin()
                    }
                }
                10005 -> {
                    mViewModel.toast.postValue("The current version is the latest version")
                }
                Invalid_Token -> {

                }
            }
        }

        eventViewModel.uploadEvent.observe(this) { uploadPostEvent ->
            when (uploadPostEvent.status) {
                UploadPostEvent.PublishStart -> {
                    CacheUtil.setUploadEvent(uploadPostEvent)
                    mViewModel.uploadFiles(uploadPostEvent) {
                        eventViewModel.uploadEvent.postValue(it)
                    }
                }
                UploadPostEvent.PublishReStart -> {
                    mViewModel.uploadFiles(uploadPostEvent) {
                        eventViewModel.uploadEvent.postValue(it)
                    }

                }
                UploadPostEvent.PublishCancel -> {
                    mViewModel.cancelUpload(uploadPostEvent)
                }
            }
        }
    }


    private fun showUpdateDialog(updateBean: UpdateBean) {
        updateBean.let {
            when {
                it.whetherToForceUpdate -> {
                    showDialogExt(
                        it.versionDescribed,
                        "New Update Available V${it.currentVersion}",
                        autoDismiss = false,
                        negative = "Update Now"
                    ) {
                        launchAppDetail(BuildConfig.APPLICATION_ID)
                    }
                }
                else -> {
                    showDialogExt(
                        it.versionDescribed,
                        "New Update Available V${it.currentVersion}",
                        negative = "Update Now",
                        positive = "Later"
                    ) {
                        launchAppDetail(BuildConfig.APPLICATION_ID)
                    }
                }
            }
        }
    }

    private fun launchAppDetail(appPkg: String) {    //appPkg 是应用的包名
        val GOOGLE_PLAY = "com.android.vending"//这里对应的是谷歌商店，跳转别的商店改成对应的即可
        try {
            if (TextUtils.isEmpty(appPkg))
                return
            val uri = Uri.parse("market://details?id=$appPkg")
            val intent = Intent(Intent.ACTION_VIEW,uri)
            intent.setPackage(GOOGLE_PLAY)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivityForResult(intent,1020)
        } catch (e: Exception) {

        }
    }

    override fun onBackPressed() {
        val nav = supportFragmentManager.findFragmentById(R.id.host_fragment)?.findNavController() ?: return super.onBackPressed()
        val label = nav.currentDestination?.label
        val isDiscoverPeople = label?.contains("DiscoverPeopleFrg",true)
        val isEditPost = label?.contains("EditPost",true)
        when {
            isDiscoverPeople == true -> nav.goMain()
            isEditPost == true -> {
                eventViewModel.onBackPressed.postValue(label.toString())
            }
            else -> super.onBackPressed()
        }
    }
}